package cn.edu.swu.myapplication1

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.Button
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // 第一个按钮点击后显示toast小字
        val button1: Button = findViewById(R.id.button1)
        button1.setOnClickListener {
            Toast.makeText(this, "You clicked Button 1", Toast.LENGTH_SHORT).show()
        }
        // 第二个按钮点击后结束当前activity
        val button2: Button = findViewById(R.id.button2)
        button2.setOnClickListener {
            finish()
        }
//        第三个按钮实现跳转到activity2
        val button3: Button = findViewById(R.id.jumpButton)
        button3.setOnClickListener {
            val data:String = "content from activity1"
            val intent = Intent(this, SecondActivity::class.java)
            intent.putExtra("extra_data", data)
//            startActivity(intent) // 不需要返回结果
            startActivityForResult(intent, 1)
        }
    }

    // 处理activity2销毁后，跳转到a1需要做的事
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            1 -> if (resultCode == RESULT_OK) {
                val returnedData = data?.getStringExtra("back_data")
                Log.d("FirstActivity", "returned data is $returnedData")
            }
        }
    }


    //    右上角三个点
    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.main, menu)
        return true
    }

//    右上角扩展菜单项目，点击后的行为
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.add_item -> Toast.makeText(this, "You clicked Add",
                Toast.LENGTH_SHORT).show()
            R.id.remove_item -> Toast.makeText(this, "You clicked Remove",
                Toast.LENGTH_SHORT).show()
        }
        return true
    }



}